﻿using System.Text.Json;

namespace MiniJob.RestClient;

public class DefaultRestClient(IHttpClientFactory httpClientFactory) : IRestClient
{
    private HttpClient GetDefaultClient()
    {
        return httpClientFactory.CreateClient(Global.DefaultHttpClientName);
    }

    public async Task<T> GetAsync<T>(string url, Dictionary<string, string>? headers = null, CancellationToken cancellationToken = default)
    {
        using var resp = await GetAsync(url, headers, cancellationToken);
        resp.EnsureSuccessStatusCode();

        var json = await resp.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<T>(json)!;
    }

    public async Task<T> PostAsync<T>(string url, object data, Dictionary<string, string>? headers = null, CancellationToken cancellationToken = default)
    {
        using var resp = await PostAsync(url, data, headers, cancellationToken);

        resp.EnsureSuccessStatusCode();

        var json = await resp.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<T>(json)!;
    }

    public Task<HttpResponseMessage> PostAsync(string url, object data, Dictionary<string, string>? headers = null, CancellationToken cancellationToken = default)
    {
        var httpclient = GetDefaultClient();
        if (headers != null)
        {
            foreach (var header in headers)
            {
                httpclient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
        }

        var jsondata = "";
        if (data != null)
        {
            jsondata = JsonSerializer.Serialize(data);
        }
        var stringContent = new StringContent(jsondata,
            new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));

        return httpclient.PostAsync(url, stringContent, cancellationToken);
    }

    public Task<HttpResponseMessage> GetAsync(string url, Dictionary<string, string>? headers = null, CancellationToken cancellationToken = default)
    {
        var httpclient = GetDefaultClient();
        if (headers != null)
        {
            foreach (var header in headers)
            {
                httpclient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
        }

        return httpclient.GetAsync(url, cancellationToken);
    }
}
